package com.osfw.dbadminer.service.config.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.dbadminer.entity.config.DbaConfigProcess;
import com.osfw.dbadminer.enums.DbOperType;
import com.osfw.dbadminer.mapper.config.DbaConfigProcessMapper;
import com.osfw.dbadminer.service.config.IDbaConfigProcessService;
import com.osfw.framework.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据库操作审批流程配置 服务层处理
 */
@Service
public class DbaConfigProcessServiceImpl extends ServiceImpl<DbaConfigProcessMapper, DbaConfigProcess> implements IDbaConfigProcessService {

    @Override
    public List<DbaConfigProcess> selectProcessList(DbaConfigProcess process) {
        LambdaQueryWrapper<DbaConfigProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DbaConfigProcess::getConnectId, process.getConnectId());
        queryWrapper.eq(StringUtils.isNotEmpty(process.getDatabaseName()), DbaConfigProcess::getDatabaseName, process.getDatabaseName());
        queryWrapper.eq(StringUtils.isNotEmpty(process.getDatatableName()), DbaConfigProcess::getDatatableName, process.getDatatableName());
        List<DbaConfigProcess> list = list(queryWrapper);
        List<String> operTypes = list.stream().map(x -> x.getOperType()).collect(Collectors.toList());
        DbOperType.getDbOperTypeList().entrySet().stream().forEach(entry -> {
            if(!operTypes.contains(entry.getKey())){
                DbaConfigProcess config = new DbaConfigProcess().setConnectId(process.getConnectId())
                        .setDatabaseName(process.getDatabaseName())
                        .setDatatableName(process.getDatatableName())
                        .setOperType(entry.getKey());
                list.add(config);
            }
        });
        return list;
    }

    @Override
    public boolean setupProcess(Long connectId, String databaseName, String datatableName, String operType, String procKey) {
        LambdaUpdateWrapper<DbaConfigProcess> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DbaConfigProcess::getConnectId, connectId);
        updateWrapper.eq(StringUtils.isNotEmpty(databaseName), DbaConfigProcess::getDatabaseName, databaseName);
        updateWrapper.eq(StringUtils.isNotEmpty(datatableName), DbaConfigProcess::getDatatableName, datatableName);
        updateWrapper.eq(DbaConfigProcess::getOperType, operType);
        return saveOrUpdate(new DbaConfigProcess().setProcKey(procKey), updateWrapper);
    }

}
